package com.hzhc.service.impl;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.TemplateExportParams;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzhc.common.FileExcelUtil;
import com.hzhc.entity.*;
import com.hzhc.enumBean.SendMsgType;
import com.hzhc.mapper.*;
import com.hzhc.service.PushService;
import com.hzhc.service.SysMsgNotifyService;
import com.hzhc.service.TrainPlanDetailService;
import com.hzhc.utils.HttpsPostUtil;
import com.hzhc.utils.ResultUtil;
import com.hzhc.vo.*;
import lombok.RequiredArgsConstructor;
import org.apache.poi.ss.formula.functions.T;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cglib.core.Local;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 消息通知 服务实现类
 * </p>
 *
 * @author 1
 * @since 2024-09-03
 */
@Service
@RequiredArgsConstructor
public class SysMsgNotifyServiceImpl extends ServiceImpl<SysMsgNotifyMapper, SysMsgNotify> implements SysMsgNotifyService {

    private final PushService pushService;
    private final SysMenuMapper menuMapper;
    private final SysYzsMenuMapper yzsMenuMapper;
    private final SysUserMapper userMapper;
    private final UserMemberMapper memberMapper;
    private final TrainPlanMapper trainPlanMapper;
    private final TrainPlanDetailMapper detailMapper;
//    private final TrainPlanDetailService detailService;
    private final SysOrganizationMapper organizationMapper;





    //-----参数------
    List<Long> userIds = new ArrayList<>();//消息发送对象id集合
    String msgContent = null;//消息内容
    String title =null;//消息标题
    String msgUrl =null;//要跳转的路由： 【/baseinfo/planapprovel】
    String urlId =null;//跳转路由 数据的id
    String urlName =null;//跳转路由的菜单name：立项审批、任务管理

    //yzs 消息提醒列表
    @Override
    public List<SysMsgNotifyVo> getList(Page<SysMsgNotifyVo> page, SysMsgNotifyVo vo) {
        IPage<SysMsgNotifyVo> iPage = baseMapper.getList(page,vo);
        return iPage.getRecords();
    }

    @Override
    public ResultUtil<T> updateReadState(SysMsgNotify notify) {
        SysMsgNotify notify1 = getById(notify.getId());
        notify1.setMsgStatus(1);
        boolean b = updateById(notify1);
        if (b){
            return ResultUtil.ok();
        }
        return ResultUtil.fail();
    }

    @Override
    public List<SysMsgNotifyVo> getCmsList(Page<SysMsgNotifyVo> page, SysMsgNotifyVo vo) {
        IPage<SysMsgNotifyVo> iPage = new Page<>();
        if (vo.getUserId()==1){//管理员 看所有
            iPage = baseMapper.getList(page,vo);
        }else{//CMS
            SysUser user = userMapper.selectById(vo.getUserId());
            SysOrganization one = organizationMapper.selectById(user.getOrgId());
            if ("SC".equals(one.getCode())){//市场部
                iPage = baseMapper.getCmsList(page,vo);
            }else{//运营部
                iPage = baseMapper.getCmsList1(page,vo);
            }
        }
        return iPage.getRecords();
    }

    //cms操作----提醒yzs公司用户 卸车完工提醒
    @Override
    public void saveMsg(TrainPlan plan, List<UserMemberVo> ids) {
        //没有发送对象
        if (ids==null || ids.size()==0){
            return;
        }
//        userIds = ids.stream().map(UserMemberVo::getId).collect(Collectors.toList());//发送对象id集合
        msgUrl = yzsMenuMapper.getUrlByName(SendMsgType.TX.getName());//跳转路由 /sysmsg/SysMsgList

        List<SysMsgNotify> list = new ArrayList<>();
        for (UserMemberVo receiveUser : ids) {
            SysMsgNotify msg = new SysMsgNotify();
            msg.setUserId(plan.getUpdateUserId().intValue());//操作人id
            msg.setUserName(userMapper.selectById(plan.getUpdateUserId()).getRealname());//操作人name
            msg.setNotifyUserId(receiveUser.getId().intValue());//发送对象id
            msg.setMsgTitle(SendMsgType.WG.getName());//消息标题
            msg.setMsgUrl(msgUrl);//跳转路由
            msg.setPhone(receiveUser.getTelephone());//对象手机号
            msg.setCompanyId(receiveUser.getCompanyId());//发送对象公司
            msg.setMsgContent("【卸车完工】贵公司从{"+receiveUser.getSendPort()+"}发出的集装箱已到达阳逻铁水联运示范基地一期，请尽快至网上服务厅办理提箱手续，以免超期产生不必要的额外费用，感谢您的配合!");
            msg.setCreateTime(LocalDateTime.now());
            msg.setDataId(plan.getId());//班列号(数据id)
            msg.setUrlName("消息提醒");
            list.add(msg);
        }
        saveBatch(list);//批量add消息

        for (SysMsgNotify notify : list) {

            JSONObject webSocketMsg = new JSONObject();
            webSocketMsg.put("msg",notify.getMsgContent());//消息内容
            webSocketMsg.put("type","yzstx");//完工提醒
            webSocketMsg.put("id",notify.getId());//
            webSocketMsg.put("url",notify.getMsgUrl());
            webSocketMsg.put("urlId",notify.getUrlId());
            webSocketMsg.put("title",notify.getMsgTitle());
            //推送至websocket
            pushService.pushMsgToOne(notify.getNotifyUserId().toString(),webSocketMsg.toJSONString());
        }

        userIds.clear();
        msgContent = null;
        title = null;
        msgUrl = null;
        urlId = null;
        urlName = null;
        list.clear();

    }

    //yzs提交 业务  cms市场部人员审核
    @Override
    public void saveYwMsg(YwOrder order,String url) {
        List<SysUser> userList = userMapper.selectOrgUserList("SC");//市场部人员
//        userIds = userList.stream().map(SysUser::getId).collect(Collectors.toList());
        String urlName1 = "";
        if ("TK".equals(order.getOrderType())){
            urlName1 = SendMsgType.TK.getName();//提空
        }else if ("KJ".equals(order.getOrderType())){
            urlName1 = SendMsgType.ZJ0.getName();//空进
        }else if ("ZJ".equals(order.getOrderType())){//重进
//            if (order.getOrderState()==0 ||order.getOrderState()==1){
                urlName1 = SendMsgType.ZJ0.getName();//0||1 普通发运
//            }else{
//                urlName1 = SendMsgType.ZJ2.getName();//2 水转铁
//            }
        }else if ("TZ".equals(order.getOrderType())){
            urlName1 = SendMsgType.TZ.getName();//提重
        }else if ("SGJ".equals(order.getOrderType())){
            urlName1 = SendMsgType.SGJ.getName();//散改集
        }else if ("TZHK".equals(order.getOrderType())){
            urlName1 = SendMsgType.TZHK.getName();//提重回空
        }else if ("HK".equals(order.getOrderType())){
            urlName1 = SendMsgType.HK.getName();//还空箱
        }

        msgUrl = menuMapper.getUrlByName(urlName1);//点击右上角消息 ---cms市场部人员 ---跳转路由

        SysMenu moduleUrl = menuMapper.selectOneByName(urlName1);
        String mulu = moduleUrl.getModuleUrl();//views/business/emptyCntrEntry/EmptyCntrEntryList.vue
        String mulu1 = mulu.substring(mulu.indexOf("/") + 1, mulu.length());//business/emptyCntrEntry/EmptyCntrEntryList.vue
        String a = mulu1.substring(0,mulu1.indexOf("/"));//business
        if (msgUrl.contains(a)){//二级菜单

        }else{//三级菜单
            msgUrl="/"+a+msgUrl;
        }

        List<SysMsgNotify> list = new ArrayList<>();
        for (SysUser user : userList) {
            SysMsgNotify msg = new SysMsgNotify();
            msg.setUserId(order.getUserId().intValue());//操作人id
            if ("CMS".equals(order.getAccessPath())){
                msg.setUserName(userMapper.selectById(order.getUserId()).getRealname());//cms操作人name
            }else{
                msg.setUserName(memberMapper.selectById(order.getUserId()).getRealName());//yzs操作人name
            }

            msg.setNotifyUserId(user.getId().intValue());//发送对象id
            msg.setMsgTitle(SendMsgType.YW.getName());//消息标题
            msg.setMsgUrl(msgUrl);//跳转路由
            msg.setPhone(user.getMobile());//发送对象手机号
            msg.setOrganizationId(user.getOrgId());//发送对象部门
            msg.setMsgContent("【"+order.getCompanyName()+"】客户已提交【"+urlName1+"】业务("+order.getOrderNo()+")，请尽快受理！");
            msg.setCreateTime(LocalDateTime.now());
            msg.setDataId(order.getId().intValue());//业务id(数据id)
            msg.setUrlName(urlName1);
            list.add(msg);
        }
        saveBatch(list);//批量add消息

        List<String> result = new ArrayList<>();
        for (SysMsgNotify notify : list) {
            JSONObject webSocketMsg = new JSONObject();
            webSocketMsg.put("msg",notify.getMsgContent());//消息内容
            webSocketMsg.put("type","cmstx");//业务审核
            webSocketMsg.put("id",notify.getId());//
            webSocketMsg.put("url",notify.getMsgUrl());
            webSocketMsg.put("urlId",notify.getUrlId());
            webSocketMsg.put("title",notify.getMsgTitle());
            webSocketMsg.put("targetUserId",notify.getNotifyUserId().toString());
            result.add(webSocketMsg.toJSONString());
            //推送至websocket

//            pushService.pushMsgToOne(notify.getNotifyUserId().toString(),webSocketMsg.toJSONString());
        }
//        String url = "http://localhost:3050/hbstlypmssys/sysMsgNotify/toWebSocketMsg";
        String s = HttpsPostUtil.sendPost(result.toString(), url);

        userIds.clear();
        msgContent = null;
        title = null;
        msgUrl = null;
        urlId = null;
        urlName = null;
        list.clear();
    }

    //cms 市场部人员审核后，消息提醒至yzs发起业务客户
    @Override
    public void saveMsgToYzsCom(YwOrder order) {
        LambdaQueryWrapper<UserMember> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserMember::getDisable,0).eq(UserMember::getCompanyId,order.getCompanyId());
        List<UserMember> memberList = memberMapper.selectList(wrapper);//当前业务发起的公司的所有人
        String urlName1 = "";
        if ("TK".equals(order.getOrderType())){
            urlName1 = SendMsgType.TK.getName();//提空
        }else if ("KJ".equals(order.getOrderType())){
            urlName1 = SendMsgType.KJ.getName();//空进
        }else if ("ZJ".equals(order.getOrderType())){
            if (order.getOrderState()==0){
                urlName1 = SendMsgType.ZJ0.getName();//0普通发运
            }else if (order.getOrderState()==1){
                urlName1 = SendMsgType.ZJ1.getName();//1班列发运
            }else{
                urlName1 = SendMsgType.ZJ2.getName();//2 水转铁
            }
        }else if ("TZ".equals(order.getOrderType())){
            urlName1 = SendMsgType.TZ.getName();//提重
        }else if ("SGJ".equals(order.getOrderType())){
            urlName1 = SendMsgType.SGJ.getName();//散改集
        }else if ("TZHK".equals(order.getOrderType())){
            urlName1 = SendMsgType.TZHK.getName();//提重回空
        }else if ("HK".equals(order.getOrderType())){
            urlName1 = SendMsgType.HK.getName();//空进
        }

        msgUrl = yzsMenuMapper.getUrlByName(SendMsgType.CLYY.getName());//点击右上角消息 跳转路由(车辆预约)

        List<SysMsgNotify> list = new ArrayList<>();
        for (UserMember user : memberList) {
            SysMsgNotify msg = new SysMsgNotify();
            msg.setUserId(order.getUpdateUserId().intValue());//操作人id
            msg.setUserName(userMapper.selectById(order.getUpdateUserId()).getRealname());//操作人name
            msg.setNotifyUserId(user.getId().intValue());//发送对象id
            msg.setMsgTitle(SendMsgType.YWTG.getName());//消息标题
            msg.setMsgUrl(msgUrl);//跳转路由
            msg.setPhone(user.getTelephone());//发送对象手机号
            msg.setCompanyId(user.getCompanyId());//发送对象公司id
            msg.setMsgContent("您提交的【"+urlName1+"】业务("+order.getOrderNo()+")已受理，请查看安排车辆！");
            msg.setCreateTime(LocalDateTime.now());
            msg.setDataId(order.getId().intValue());//业务id(数据id)
            msg.setUrlName(urlName1);
            list.add(msg);
        }
        saveBatch(list);//批量add消息
        for (SysMsgNotify notify : list) {
            JSONObject webSocketMsg = new JSONObject();
            webSocketMsg.put("msg", notify.getMsgContent());//消息内容
            webSocketMsg.put("type", "yzstx");//业务审核通过
            webSocketMsg.put("id", notify.getId());//
            webSocketMsg.put("url", notify.getMsgUrl());
            webSocketMsg.put("urlId", notify.getUrlId());
            webSocketMsg.put("title", notify.getMsgTitle());
            //推送至websocket
            pushService.pushMsgToOne(notify.getNotifyUserId().toString(), webSocketMsg.toJSONString());
        }

        userIds.clear();
        msgContent = null;
        title = null;
        msgUrl = null;
        urlId = null;
        urlName = null;
        list.clear();
    }

    //cms 市场部人员审核后，消息提醒至cms运营部
    @Override
    public void saveMsgToCmsYYB(YwOrder order) {
        List<SysUser> userList = userMapper.selectOrgUserList("czyy");//运营部人员

        String urlName1 = "";
        if ("TK".equals(order.getOrderType())){
            urlName1 = SendMsgType.TK.getName();//提空
        }else if ("KJ".equals(order.getOrderType())){
            urlName1 = SendMsgType.KJ.getName();//空进
        }else if ("ZJ".equals(order.getOrderType())){
//            if (order.getOrderState()==0){
                urlName1 = SendMsgType.ZJ0.getName();//0普通发运
//            }else if (order.getOrderState()==1){
//                urlName1 = SendMsgType.ZJ1.getName();//1班列发运
//            }else{
//                urlName1 = SendMsgType.ZJ2.getName();//2 水转铁
//            }
        }else if ("TZ".equals(order.getOrderType())){
            urlName1 = SendMsgType.TZ.getName();//提重
        }else if ("SGJ".equals(order.getOrderType())){
            urlName1 = SendMsgType.SGJ.getName();//散改集
        }else if ("TZHK".equals(order.getOrderType())){
            urlName1 = SendMsgType.TZHK.getName();//提重回空
        }

        urlName = SendMsgType.JKDJ.getName();

        //运营安排作业  跳转哪里
        SysMenu one = menuMapper.selectOneByName(urlName);//点击右上角消息 跳转路由(yzs安排车辆+小程序司机同意====进卡登记)
        msgUrl = one.getModuleUrl();///jinkaregister.html

        List<SysMsgNotify> list = new ArrayList<>();
        for (SysUser user : userList) {
            SysMsgNotify msg = new SysMsgNotify();
            msg.setUserId(order.getUpdateUserId().intValue());//操作人id
            msg.setUserName(userMapper.selectById(order.getUpdateUserId()).getRealname());//操作人name
            msg.setNotifyUserId(user.getId().intValue());//发送对象id
            msg.setMsgTitle(SendMsgType.YW.getName());//消息标题
            msg.setMsgUrl(msgUrl);//跳转路由
            msg.setPhone(user.getMobile());//发送对象手机号
            msg.setOrganizationId(user.getOrgId());//发送对象部门
            msg.setMsgContent("【"+urlName1+"】业务("+order.getOrderNo()+")已受理，请安排作业！");
            msg.setCreateTime(LocalDateTime.now());
            msg.setDataId(order.getId().intValue());//业务id(数据id)
            msg.setUrlName(urlName1);
            list.add(msg);
        }
        saveBatch(list);//批量add消息

        for (SysMsgNotify notify : list) {
            JSONObject webSocketMsg = new JSONObject();
            webSocketMsg.put("msg",notify.getMsgContent());//消息内容
            webSocketMsg.put("type","cmstx");//业务审核
            webSocketMsg.put("id",notify.getId());//
            webSocketMsg.put("url",notify.getMsgUrl());
            webSocketMsg.put("urlId",notify.getUrlId());
            webSocketMsg.put("title",notify.getMsgTitle());
            //推送至websocket
            pushService.pushMsgToOne(notify.getNotifyUserId().toString(),webSocketMsg.toJSONString());
        }

        userIds.clear();
        msgContent = null;
        title = null;
        msgUrl = null;
        urlId = null;
        urlName = null;
        list.clear();
    }

    //修改 业务申请箱信息后，同意 or 驳回  ，消息提醒给yzs客户
    @Override
    public void saveCntrEditMsg(YwOrderCntrAuditVo vo, List<UserMemberVo> users) {
        if (users == null || users.size()==0){
            return;
        }
        urlName = SendMsgType.TX.getName();
        msgUrl = yzsMenuMapper.getUrlByName(urlName);
        List<SysMsgNotify> list = new ArrayList<>();

        for (UserMemberVo memberVo : users) {
            SysMsgNotify msg = new SysMsgNotify();
            msg.setUserId(vo.getUpdateUserId().intValue());//操作（审核）人
            msg.setUserName(userMapper.selectById(vo.getUpdateUserId()).getRealname());//操作人姓名
            msg.setNotifyUserId(memberVo.getId().intValue());
            msg.setMsgTitle(SendMsgType.TX.getName());
            msg.setMsgUrl(msgUrl);
            msg.setPhone(memberVo.getTelephone());
            msg.setCompanyId(memberVo.getCompanyId());
            if (vo.getAuditFlag()==1){//通过
                msg.setMsgContent("您对委托号"+vo.getOrderNo()+"内箱号("+vo.getCntrNo()+")的修改申请已同意，请及时修改！");
            }else{//驳回
                msg.setMsgContent("您对委托号"+vo.getOrderNo()+"内箱号("+vo.getCntrNo()+")的修改申请已驳回，驳回原因是"+vo.getRefugeeReason()+"，如有问题请联系场站！");
            }
            msg.setCreateTime(LocalDateTime.now());
            msg.setDataId(vo.getId().intValue());
            msg.setUrlName("消息提醒");
            list.add(msg);
        }

        saveBatch(list);

        for (SysMsgNotify notify : list) {
            JSONObject webSocketMsg = new JSONObject();
            webSocketMsg.put("msg",notify.getMsgContent());//消息内容
            webSocketMsg.put("type","yzstx");//完工提醒
            webSocketMsg.put("id",notify.getId());//
            webSocketMsg.put("url",notify.getMsgUrl());
            webSocketMsg.put("urlId",notify.getUrlId());
            webSocketMsg.put("title",notify.getMsgTitle());
            //推送至websocket
            pushService.pushMsgToOne(notify.getNotifyUserId().toString(),webSocketMsg.toJSONString());
        }
        userIds.clear();
        msgContent = null;
        title = null;
        msgUrl = null;
        urlId = null;
        urlName = null;
        list.clear();
    }

    //到达箱推送
    @Override
    public void sendMsgToCom(String zhPort, List<UserMember> users,Long userId,Integer timeNum) {
        if (users==null || users.size()==0){
            return;
        }
        msgUrl = yzsMenuMapper.getUrlByName(SendMsgType.TX.getName());//跳转路由 /sysmsg/SysMsgList


        List<SysMsgNotify> list = new ArrayList<>();
        for (UserMember receiveUser : users) {
            SysMsgNotify msg = new SysMsgNotify();
            msg.setUserId(userId.intValue());//操作人id
            msg.setUserName(userMapper.selectById(userId).getRealname());//操作人name
            msg.setNotifyUserId(receiveUser.getId().intValue());//发送对象id
            msg.setMsgTitle(SendMsgType.DDXTS.getName());//消息标题
            msg.setMsgUrl(msgUrl);//跳转路由
            msg.setPhone(receiveUser.getTelephone());//对象手机号
            msg.setCompanyId(receiveUser.getCompanyId());//发送对象公司
            msg.setMsgContent("【卸车完工】贵公司从{"+zhPort+"}发出的集装箱已到达阳逻铁水联运示范基地一期，请尽快至网上服务厅办理提箱手续，以免超期产生不必要的额外费用，感谢您的配合!");
            msg.setCreateTime(LocalDateTime.now());
            msg.setDataId(timeNum);//(数据id)组别号
            msg.setUrlName("消息提醒");
            list.add(msg);
        }
        saveBatch(list);//批量add消息

        for (SysMsgNotify notify : list) {

            JSONObject webSocketMsg = new JSONObject();
            webSocketMsg.put("msg",notify.getMsgContent());//消息内容
            webSocketMsg.put("type","yzstx");//完工提醒
            webSocketMsg.put("id",notify.getId());//
            webSocketMsg.put("url",notify.getMsgUrl());
            webSocketMsg.put("urlId",notify.getUrlId());
            webSocketMsg.put("title",notify.getMsgTitle());
            //推送至websocket
            pushService.pushMsgToOne(notify.getNotifyUserId().toString(),webSocketMsg.toJSONString());
        }

        userIds.clear();
        msgContent = null;
        title = null;
        msgUrl = null;
        urlId = null;
        urlName = null;
        list.clear();

    }

    private final static String MONTH_REPORT_EXCEL_PATH = "static/download/卸车完工提醒导出.xlsx";

    @Override
    public void exportReport(TrainPlanDetailVo vo, HttpServletRequest request, HttpServletResponse response) {
//        List<TrainPlanDetailVo> vos = detailService.getTrainPlanDetail(vo);
//        Map<String, Object> map = new HashMap<>();
//        map.put("list", vos);
//        map.put("cntrNo", vos.stream().map(TrainPlanDetailVo::getCntrNo));
//        map.put("cntrSize", vos.stream().map(TrainPlanDetailVo::getCntrSize));
//        map.put("efFlag", vos.stream().map(TrainPlanDetailVo::getEfFlag));
//        map.put("goods", vos.stream().map(TrainPlanDetailVo::getGoods));
//        map.put("waterOrder", vos.stream().map(TrainPlanDetailVo::getWaterOrder));
//        map.put("zhPort", vos.stream().map(TrainPlanDetailVo::getZhPort));
//        map.put("mdPort", vos.stream().map(TrainPlanDetailVo::getMdPort));
//        map.put("consignee", vos.stream().map(TrainPlanDetailVo::getConsignee));
//        map.put("consigner", vos.stream().map(TrainPlanDetailVo::getConsigner));
//        TemplateExportParams params = new TemplateExportParams(MONTH_REPORT_EXCEL_PATH);
//        Workbook workbook = ExcelExportUtil.exportExcel(params, map);
//        FileExcelUtil.downloadExcelIo(workbook, request, response, "卸车完工提醒");
    }


}
